package com.jd.pet.service.impl;

import com.jd.pet.domain.PetType;
import com.jd.pet.service.IPetTypeService;
import com.jd.basic.service.impl.BaseServiceImpl;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author jd
 * @since 2023-03-13
 */
@Service
public class PetTypeServiceImpl extends BaseServiceImpl<PetType> implements IPetTypeService {

    @Override
    public List<PetType> tree() {
        //查询所有的类型
        List<PetType> all = super.findAll();
        ArrayList<PetType> petTypes = new ArrayList<>();
        Map<Long, PetType> petTypeMap = all.stream().collect(Collectors.toMap(PetType::getId, petType -> petType));
        for (PetType petType : all) {
            if (petType.getPid() == null) {
                petTypes.add(petType);
            } else {
                PetType petTypePar = petTypeMap.get(petType.getPid());
                if (petTypePar != null){
                    petTypePar.getChildren().add(petType);
                }

            }
        }
        return petTypes;
    }
}
